package com.newbookstore.service;

import com.newbookstore.Model.Bookstore;
import com.newbookstore.Repository.BookstoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BookstoreServiceImpl implements BookstoreService{
    @Autowired
    private BookstoreRepository bookstoreRepository;

    @Override
    public List<Bookstore> getAllBookstore(){
        return bookstoreRepository.findAll();
    }
    @Override
    public void saveBookstore(Bookstore bookstore){
        this.bookstoreRepository.save(bookstore);
    }
    @Override
    public Bookstore getBookstoreById(long id) {
        //调用数据访问层查找指定ID的书本，返回Optional==（选择)对象
        Optional<Bookstore> optional = bookstoreRepository.findById(id);

        Bookstore bookstore = null;
        //如果存在指定id的书本
        if (optional.isPresent()) {
            //从Optional对象中获取书本对象
            bookstore = optional.get();
        } else {
            //否则抛出运行时异常
            throw new RuntimeException(" 找不到书本ID :: " + id);
        }
        return bookstore;
    }

    //删除指定id的书本
    @Override
    public void deleteBookstoreById(long id) {
        this.bookstoreRepository.deleteById(id);
    }
    @Override
    public Page<Bookstore> findPaginated(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);

        return this.bookstoreRepository.findAll(pageable);
    }

    @Override
    public List<Bookstore> findByBookname(String name) {
        List<Bookstore> bookname = bookstoreRepository.findAllByName(name);

        return bookname;
    }

    @Override
    public void updateBookstore(Bookstore bookstore) {
        bookstoreRepository.save(bookstore);
    }
}
